import { useState, useEffect, useRef } from 'react';

// 此处源码实现有问题，日后再优化
export const create = (stateCreator) => {
    let state = stateCreator((newState) => {
        state = { ...state, ...newState };
        listeners.forEach(listener => listener(state));
    });

    const listeners = new Set();

    const useStore = (selector = (state) => state) => {
        const [selectedState, setSelectedState] = useState(() => selector(state));
        const selectorRef = useRef(selector);

        useEffect(() => {
            const listener = (newState) => {
                const newSelectedState = selectorRef.current(newState);
                setSelectedState(newSelectedState);
            };
            listeners.add(listener);
            return () => listeners.delete(listener);
        }, []);

        return selectedState;
    };

    return useStore;
};
